import { Request, Response } from 'express';
import { Word } from '../models/Word';

// 获取所有单词
export const getWords = async (req: Request, res: Response) => {
  try {
    const words = await Word.find();
    res.json(words);
  } catch (error) {
    res.status(500).json({ message: '获取单词列表失败', error });
  }
};

// 获取单个单词
export const getWord = async (req: Request, res: Response) => {
  try {
    const word = await Word.findById(req.params.id);
    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }
    res.json(word);
  } catch (error) {
    res.status(500).json({ message: '获取单词失败', error });
  }
};

// 创建单词
export const createWord = async (req: Request, res: Response) => {
  try {
    const word = new Word(req.body);
    await word.save();
    res.status(201).json({
      message: '创建单词成功',
      word
    });
  } catch (error) {
    res.status(500).json({ message: '创建单词失败', error });
  }
};

// 更新单词
export const updateWord = async (req: Request, res: Response) => {
  try {
    const word = await Word.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    
    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }
    
    res.json({
      message: '更新单词成功',
      word
    });
  } catch (error) {
    res.status(500).json({ message: '更新单词失败', error });
  }
};

// 删除单词
export const deleteWord = async (req: Request, res: Response) => {
  try {
    const word = await Word.findByIdAndDelete(req.params.id);
    
    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }
    
    res.json({ message: '删除单词成功' });
  } catch (error) {
    res.status(500).json({ message: '删除单词失败', error });
  }
}; 